package view;

import java.time.LocalDateTime;
import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.nio.file.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class EmployeeView {
    private static Map<String, LocalDateTime> clockInTimes = new HashMap<>();
    private static Map<String, Duration> workDurations = new HashMap<>();
    private static Map<String, LocalDateTime> lastClockInTimes = new HashMap<>();
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    public static void displayMenu() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("1. 上班打卡");
            System.out.println("2. 下班打卡");
            System.out.println("3. 查看工作时长");
            System.out.println("4. 返回主菜单");
            System.out.print("选择一个选项: ");

            int option = scanner.nextInt();
            scanner.nextLine();  // Consume newline

            switch (option) {
                case 1:
                    clockIn(scanner);
                    break;
                case 2:
                    clockOut(scanner);
                    break;
                case 3:
                    viewWorkDuration(scanner);
                    break;
                case 4:
                    System.out.println("返回主菜单.");
                    return;
                default:
                    System.out.println("无效选项. 请重试.");
            }
        }
    }

    private static void clockIn(Scanner scanner) {
        System.out.print("输入员工ID: ");
        String employeeId = scanner.nextLine();
        LocalDateTime now = LocalDateTime.now();

        if (clockInTimes.containsKey(employeeId)) {
            LocalDateTime lastClockInTime = lastClockInTimes.get(employeeId);
            if (lastClockInTime != null && Duration.between(lastClockInTime, now).toMinutes() < 10) {
                System.out.println("距离上次打卡不到10分钟，请等待10分钟再打卡。");
                return;
            }
        }

        clockInTimes.put(employeeId, now);
        lastClockInTimes.put(employeeId, now);

        // Save the clock-in record to a file
        saveClockRecord(employeeId, "上班", now);

        System.out.println("已成功打卡上班，加油，祝你工作顺利!（我会随时在监控看你的，别偷懒）");
    }

    private static void clockOut(Scanner scanner) {
        System.out.print("输入员工ID: ");
        String employeeId = scanner.nextLine();
        LocalDateTime clockInTime = clockInTimes.get(employeeId);

        if (clockInTime != null) {
            LocalDateTime now = LocalDateTime.now();
            Duration workDuration = Duration.between(clockInTime, now);
            workDurations.put(employeeId, workDurations.getOrDefault(employeeId, Duration.ZERO).plus(workDuration));

            clockInTimes.remove(employeeId);
            lastClockInTimes.remove(employeeId);

            // Save the clock-out record to a file
            saveClockRecord(employeeId, "下班", now);

            System.out.println("已成功打卡下班，谢谢你的努力，回家路途注意安全，明天别忘了来上班!");
        } else {
            System.out.println("找不到打卡记录。请确认你是否已经上班打卡。");
        }
    }

    private static void viewWorkDuration(Scanner scanner) {
        System.out.print("输入员工ID: ");
        String employeeId = scanner.nextLine();
        Duration duration = workDurations.get(employeeId);

        if (duration != null) {
            long hours = duration.toHours();
            long minutes = duration.toMinutes() % 60;
            System.out.println("员工 " + employeeId + " 总工作时长: " + hours + " 小时 " + minutes + " 分钟");
        } else {
            System.out.println("找不到工作时长记录。请确认你是否有过打卡记录。");
        }
    }

    private static void saveClockRecord(String employeeId, String action, LocalDateTime dateTime) {
        String fileName = "employee_" + employeeId + "_records.txt";
        String record = String.format("%s: %s 打卡时间: %s%n", action, dateTime.format(DATE_FORMATTER), dateTime.format(DateTimeFormatter.ofPattern("HH:mm")));

        try {
            Files.write(Paths.get(fileName), record.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException e) {
            System.out.println("无法保存打卡记录: " + e.getMessage());
        }
    }
}
